package it.anyplace.jxpath4json;

import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.jxpath.JXPathContext;

public class App {

    public static void main(String[] args) throws IOException {
        String jsonStr = null, xpathStr = null;
        boolean prettyPrint = false;
        for (String arg : args) {
            if (Objects.equal(arg, "-p")) {
                prettyPrint = true;
            } else if (Objects.equal(arg, "-h") || Objects.equal(arg, "--help")) {
                System.err.println("usage: $0 [-p] <xpath> [file]\n\tif no file is proided, will read from stdin\n\tresult data will print to stdout");
            } else if (xpathStr == null) {
                xpathStr = Strings.emptyToNull(arg);
            } else {
                File file = new File(arg);
                if (file.exists()) {
                    jsonStr = Strings.emptyToNull(FileUtils.readFileToString(file));
                } else {
                    jsonStr = Strings.emptyToNull(arg);
                }
            }
        }
        if (jsonStr == null) {
            jsonStr = Strings.emptyToNull(IOUtils.toString(System.in));
        }
        Preconditions.checkNotNull(jsonStr);
        Preconditions.checkNotNull(xpathStr);

        Gson gson = prettyPrint ? new GsonBuilder().setPrettyPrinting().create() : new Gson();

        Object json = gson.fromJson(jsonStr, Object.class);

        JXPathContext jXPathContext = JXPathContext.newContext(json);
        Iterator iterator = jXPathContext.iterate(xpathStr);
        while (iterator.hasNext()) {
            gson.toJson(iterator.next(), System.out);
            System.out.println();
        }
    }
}
